package org.i1510.base.utils.io;

import java.io.IOException;
import java.io.InputStream;

/**
 * 解密流
 * 
 * @author 叶中奇
 * 
 */
public class DecryptionInputStream extends AbstractInputStream {
	public DecryptionInputStream(InputStream originStream) throws IOException {
		super(originStream);
	}

	public DecryptionInputStream(InputStream originStream, int encryptionMode)
			throws IOException {
		super(originStream, encryptionMode);
	}

	private boolean noEncryption;

	@Override
	protected void init() throws IOException {
		noEncryption = (cryptionMode == 0);
		if (noEncryption) {
			return;
		}
		int len = markBytes.length;
		// 若字节数小于加密字节数，则不做处理
		// 去掉该判断，因为oracle下orgIn.available()返回为0，导致解密失败
		// if (orgIn.available() < len) {
		// noEncryption = true;
		// return;
		// }
		// 校验前面len个字节是否合法
		byte[] b = new byte[len];
		originStream.read(b);
		for (int i = 0; i < len; i++) {
			if (format(b[i] + 128) != (markBytes[i] + 128)) {
				additionalBytes = b;
				noEncryption = true;
				return;
			}
		}
	}

	@Override
	protected void format(byte[] b, int off, int len) {
		if (noEncryption)
			return;
		for (int i = off; i < len; i++) {
			if (b[i] == -128)
				b[i] = 127;
			else
				b[i]--;
		}
	}

	@Override
	protected int format(int i) {
		if (noEncryption)
			return i;
		if (i == -1)
			return -1;
		if (i == 0)
			return 255;
		return i - 1;
	}
}
